package org.benetech.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * Utilities for handling Excel spreadsheets.
 * @author Reuben Firmin
 */
public final class XLSUtils {

	/**
	 * Get an arbitrary number of columns as strings, from the entire worksheet.
	 * @param file The spreadsheet (xls) file
	 * @param sheet The number of the worksheet; left to right, starts at 0.
	 * @param columns The columns to get; left to right, starts at 0.
	 * @return Never null
	 * @throws IOException If file access fails
	 */
	public static String[][] getColumns(final File file, final int sheet, final int... columns) throws IOException {
	    final POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
	    final HSSFWorkbook wb = new HSSFWorkbook(fs);
	    final HSSFSheet worksheet = wb.getSheetAt(sheet);

	    final int min = worksheet.getFirstRowNum();
	    final int max = worksheet.getLastRowNum();
	    final int size = max - min + 1;
	    final String[][] rows = new String[size][columns.length];
 	    int colIndex = 0;
 	    int rowIndex = 0;
	    for (int i = min; i <= max; i++) {
	    	colIndex = 0;
	    	final HSSFRow row = worksheet.getRow(i);
	    	for (int column : columns) {
	    		final HSSFCell cell = row.getCell((short) column);
	    		rows[rowIndex][colIndex] = cell.getRichStringCellValue().getString();
	    		colIndex++;
	    	}
	    	rowIndex++;
	    }
	    return rows;
	}
}
